-- Code inspired by tekability (by tekkub) http://www.wowinterface.com/downloads/info9235

-- I used and loved so much this little addon till a friend of 
-- mine reports to me that the char durability numbers conflicts with 
-- other addon (like http://www.wowinterface.com/downloads/info21014-ItemLevelDisplay.html)

-- Because what we really use was only the tekability LDB feed I decide to rewrite
-- it removing everything else than LDB feed.

-- So mydurability is born. It shows only the min durability of your items (even if adding all durability in tooltip could be easily done).


local ADDON = ...

local math_min = math.min
local string_format = string.format
local string_gsub = string.gsub
local table_insert = table.insert
local prgname = "MyDurability"
local idx, perc
local format_color = "|cff%02x%02x%02x%s"

local durabilities = {}

local slots = {
   "HeadSlot",
   "ShoulderSlot",
   "ChestSlot",
   "WristSlot",
   "HandsSlot",
   "WaistSlot",
   "LegsSlot",
   "FeetSlot",
   "MainHandSlot",
   "SecondaryHandSlot",
}

local text_color = {
	{0,1,0},
	{1,1,0},
	{1,0.5,0},
	{1,0,0},
}

local ldb = LibStub:GetLibrary("LibDataBroker-1.1")
local dataobj = ldb:NewDataObject("MyDurability", {
	type = "data source",
	icon = "Interface\\Minimap\\Tracking\\Repair",
	text = "100%",
})

local frame_md = CreateFrame("Frame", ADDON.."_LDB")
frame_md:RegisterEvent("UPDATE_INVENTORY_DURABILITY")
frame_md:SetScript("OnEvent", function(self, event, ...)
	
	local mindurability = 1
	durabilities = {}
	
	for idx=1, #slots do
		local slotid = GetInventorySlotInfo(slots[idx])
		local durability, maxdurability = GetInventoryItemDurability(slotid)  
		if durability and maxdurability and maxdurability ~= 0 then	
			table_insert(durabilities, tostring(string_format("%d", (durability/maxdurability)*100)))
			mindurability = math_min(durability/maxdurability, mindurability)		  
		end 
	end	
	
	if     mindurability >= 0  and  mindurability < 0.25   then perc = 4
	elseif mindurability >= 0.25 and  mindurability < 0.50   then perc = 3
	elseif mindurability >= 0.50 and  mindurability < 0.75   then perc = 2
	elseif mindurability >= 0.75 and mindurability <= 1 then perc = 1
	end
	
	dataobj.text = string_format(format_color, text_color[perc][1]*255, text_color[perc][2]*255, text_color[perc][3]*255, string_format("%d%%",mindurability*100)).."|r"

end
)

function dataobj:OnEnter()
	GameTooltip:SetOwner(self, "ANCHOR_NONE")
	GameTooltip:SetPoint("TOPLEFT", self, "BOTTOMLEFT")
	GameTooltip:ClearLines()
	dataobj.OnTooltipShow(GameTooltip)
	GameTooltip:Show()
end

function dataobj:OnTooltipShow()
	-- GameTooltip:AddLine(prgname .. " v" .. GetAddOnMetadata(prgname, "Version"))
	GameTooltip:AddLine(prgname)
	GameTooltip:AddLine(" ")
	for idx=1, #slots do
		if durabilities[idx] then 
			GameTooltip:AddDoubleLine(string_gsub(slots[idx],"Slot",""), durabilities[idx],1,1,1, 1,1,1)
		end
	end
end

function dataobj:OnLeave()
	GameTooltip:Hide()
end

